package com.example.biji.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.biji.dao.UserDao;
import com.example.biji.model.User;
import com.example.biji.R;

public class UserSettingsActivity extends AppCompatActivity {
    private EditText etUsername, etOldPassword, etNewPassword;
    private Button btnSave, btnLogout;
    private UserDao userDao;
    private int userId;
    private String currentUsername;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_settings);

        userId = getIntent().getIntExtra("userId", -1);
        currentUsername = getIntent().getStringExtra("username");

        if (userId == -1) {
            Toast.makeText(this, "用户ID获取失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        initViews();
        loadUserInfo();
        setupListeners();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_settings_username);
        etOldPassword = findViewById(R.id.et_settings_old_password);
        etNewPassword = findViewById(R.id.et_settings_new_password);
        btnSave = findViewById(R.id.btn_settings_save);
        btnLogout = findViewById(R.id.btn_settings_logout);
        userDao = new UserDao(this);
    }

    private void loadUserInfo() {
        etUsername.setText(currentUsername);
    }

    private void setupListeners() {
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserInfo();
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }

    private void updateUserInfo() {
        String newUsername = etUsername.getText().toString().trim();
        String oldPassword = etOldPassword.getText().toString().trim();
        String newPassword = etNewPassword.getText().toString().trim();

        Log.d("UserSettingsActivity", "更新用户信息: " + newUsername);

        if (!newUsername.equals(currentUsername)) {
            // 检查新用户名是否已存在
            User existingUser = userDao.queryUser(newUsername);
            if (existingUser != null) {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        boolean hasChanges = false;

        // 更新用户名
        if (!newUsername.equals(currentUsername)) {
            User user = new User();
            user.setId(userId);
            user.setUsername(newUsername);
            if (userDao.updateUsername(user)) {
                Log.d("UserSettingsActivity", "用户名更新为: " + newUsername);
                currentUsername = newUsername;
                hasChanges = true;
            } else {
                Toast.makeText(this, "用户名更新失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        // 更新密码
        if (!TextUtils.isEmpty(oldPassword) && !TextUtils.isEmpty(newPassword)) {
            // 验证旧密码并更新新密码
            User user = userDao.queryUserById(userId);
            if (user != null && user.getPassword().equals(oldPassword)) {
                // 更新数据库中的密码
                user.setPassword(newPassword);
                if (userDao.updatePassword(user)) {
                    Log.d("UserSettingsActivity", "密码已更新");
                    Toast.makeText(this, "密码更新成功", Toast.LENGTH_SHORT).show();
                    hasChanges = true;
                } else {
                    Toast.makeText(this, "密码更新失败", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "旧密码错误", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if (hasChanges) {
            Toast.makeText(this, "设置更新成功", Toast.LENGTH_SHORT).show();

            // 返回更新后的用户名到主界面
            Intent resultIntent = new Intent();
            resultIntent.putExtra("username", currentUsername);
            setResult(RESULT_OK, resultIntent);
            finish(); // 确保在更新后关闭设置页面
        } else {
            Toast.makeText(this, "没有更改需要保存", Toast.LENGTH_SHORT).show();
        }
    }

    private void logout() {
        Log.d("UserSettingsActivity", "用户登出");

        // 清除登录状态
        getSharedPreferences("login_prefs", MODE_PRIVATE)
                .edit()
                .clear()
                .apply();

        // 返回登录页
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}